package com.online_exam.controller.student;

import com.auth0.jwt.JWT;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.online_exam.base.RestResponse;
import com.online_exam.base.UserType;
import com.online_exam.domain.Message;
import com.online_exam.domain.MessageUser;
import com.online_exam.domain.User;
import com.online_exam.repository.UserMapper;
import com.online_exam.service.MessageService;
import com.online_exam.service.UserService;
import com.online_exam.util.JwtUtil;
import com.online_exam.viewmodel.student.user.MessageRequestVM;
import com.online_exam.viewmodel.student.user.MessageResponseVM;
import com.online_exam.viewmodel.student.user.MessageUserPage;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController("StudentUserController")
@RequestMapping("/api/student/user/message")
public class MessageController {
    @Autowired
    private MessageService messageService;
    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private UserService userService;

    @PostMapping("/page")
    public RestResponse<MessageUserPage> page(@RequestBody MessageRequestVM requestVM, HttpServletRequest request){

       //需要获取当前用户id
        String token = request.getHeader("token");
        String userName=JWT.decode(token).getClaim("userName").asString();
        User user = userService.selectByUsername(userName);
        int userid = user.getId();


        requestVM.setReceiveUserId(userid);
        Page<Object> page = PageHelper.startPage(requestVM.getPageIndex(), requestVM.getPageSize());
        MessageUserPage messageUserPage=new MessageUserPage(page.getPageNum(),page.getPageSize());

        List<MessageUser> messageUsers = messageService.selectByUserId(userid);
        List<Integer> ids = messageUsers.stream().map((msg -> msg.getMessageId())).collect(Collectors.toList());
        List<Message> list = ids.size()==0?null:messageService.selectByUserMsgId(ids);
        List<MessageResponseVM> vmList = messageUsers.stream().map((messageUser -> {
            MessageResponseVM messageResponseVM = modelMapper.map(messageUser, MessageResponseVM.class);
            list.stream().filter(message ->
                    messageUser.getMessageId().equals(message.getId())
            ).findFirst().ifPresent(m -> {
                messageResponseVM.setContent(m.getContent());
                messageResponseVM.setTitle(m.getTitle());
                messageResponseVM.setSendUserName(m.getSendUserName());

            });
            messageResponseVM.setCreateTime(messageUser.getCreateTime().toString());
            return messageResponseVM;
        })).collect(Collectors.toList());
        messageUserPage.setList(vmList);

        return RestResponse.ok(messageUserPage);
    }

    @PostMapping("/read/{id}")
    public RestResponse read(@PathVariable Integer id){
        messageService.readByUser(id);
        return RestResponse.ok();
    }

    @PostMapping("/unreadCount")
    public RestResponse unreadCount(HttpServletRequest request){
        //需要从token中获取id
        int id = JwtUtil.DecodeByToken(request,userService).getId();
        int count = messageService.unReadCount(id);
        return RestResponse.ok(count);
    }
}
